package com.hs.telepass.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import com.hs.teleform.R;
import com.hs.telepass.ui.View.LoadingDialog;
import com.hs.telepass.utils.ToastUtil;

public abstract class BaseFragment extends Fragment {
    protected Context context;
    private LocalBroadcastManager manager;
    public LoadingDialog loadingDialog;

    @Override
    public void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        context = getActivity();
        IntentFilter intentFilter = getIntentFilter();
        if (null != intentFilter) {
            manager = LocalBroadcastManager.getInstance(context);
            manager.registerReceiver(receiver, getIntentFilter());
        }

        loadingDialog = new LoadingDialog(context);

    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
        manager.unregisterReceiver(receiver);
        super.onDestroy();
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == intent)
                return;
            handleOnReceive(intent);
        }
    };

    /**
     * 注册LocalBroadcastManager的IntentFilter 不注册return null;
     *
     * @return
     */
    public abstract IntentFilter getIntentFilter();

    /***
     * onReceive的回调函数
     */
    public abstract void handleOnReceive(Intent intent);


    /**
     * 显示加载状态框
     * @param msgId
     *          string资源id
     * */
    public void dialogLoading(int msgId){
        loadingDialog.setMessage(getString(msgId));
        loadingDialog.show();
    }

    /**
     * 显示加载状态框
     * @param msg
     * */
    public void dialogLoading(String msg){
        loadingDialog.setMessage(msg);
        loadingDialog.show();
    }

    /**
     * 显示正在加载弹出框
     */
    public void dialogLoading(){
        dialogLoading(R.string.loading);
    }

    /**
     * 错误的时候, 让dialog不显示, 弹出toast错误信息
     * @param msg
     */
    public void dialogError(String msg){
        dialogDimiss();
        ToastUtil.showMessageInShort(context, msg);
    }

    /**
     * 错误的时候, 让dialog不显示, 弹出toast错误信息
     * @param msgId
     *          字符串资源id
     */
    public void dialogError(int msgId){
        dialogLoading(getString(msgId));
    }

    public void dialogError(){
        dialogError(R.string.fail_network);
    }


    public void dialogDimiss(){
        if(null != loadingDialog && loadingDialog.isShowing()){
            loadingDialog.dismiss();
        }
    }

}
